package bar.dark.lee.widget;

import java.util.Calendar;

import bar.dark.lee.BDConstents;
import bar.dark.lee.IntroActivitiy;
import bar.dark.lee.R;
import bar.dark.lee.common.DBSQLite;
import bar.dark.lee.common.DBSQLite.ParseSelectData;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.util.Log;
import android.widget.RemoteViews;
import android.widget.TextView;

public class AccountBookWidget3x2 extends AppWidgetProvider
{
	public final static int alarmRequestCode = 4;
	
	@Override
	public void onUpdate(Context context, AppWidgetManager appWidgetManager,
			int[] appWidgetIds)
	{
		appWidgetIds = appWidgetManager.getAppWidgetIds(new ComponentName(context, getClass()));
		
		super.onUpdate(context, appWidgetManager, appWidgetIds);
		
//		for (int i = 0; i < appWidgetIds.length; i++)
//		{
//			setDataUpdate(context, appWidgetIds[i]);
//		}
		
		startDataUpdate(context);
	}
	
	public void startDataUpdate(Context context)
	{
		// 알람이 있음 알람을 종료
		AlarmManager am = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
		Intent removeintent = new Intent(context, WidgetService3x2.class);
	    PendingIntent sender = PendingIntent.getService(context, 
	    		BDConstents.WIDGET_ALARM_CODE_3x2, removeintent, 0);
	    am.cancel(sender);
	    context.stopService(removeintent);
		
	    // 알람을 실행
		Intent startIntent = new Intent(context, WidgetService3x2.class);
		PendingIntent pendingIntent = PendingIntent.getService(context, 
				BDConstents.WIDGET_ALARM_CODE_3x2, startIntent, 0);
		Calendar cal = Calendar.getInstance();
		AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
		alarmManager.setRepeating(AlarmManager.RTC, cal.getTimeInMillis(), 10000, pendingIntent);
	}
	
	@Override
	public void onEnabled(Context context)
	{
		super.onEnabled(context);
		
		// 메모리 제거시 죽일 프로세스에 선택되지 않도록 하는 코드
		PackageManager pm = context.getPackageManager();
		pm.setComponentEnabledSetting(new ComponentName("bar.dark.lee", ".widget.AccountBookWidget3x2"),
				PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
				PackageManager.DONT_KILL_APP);
	}
	
	@Override
	public void onDeleted(Context context, int[] appWidgetIds)
	{
		super.onDeleted(context, appWidgetIds);
		
		AlarmManager am = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
		Intent intent = new Intent(context, WidgetService3x2.class);
	    PendingIntent sender = PendingIntent.getService(context, 
	    		BDConstents.WIDGET_ALARM_CODE_3x2, intent, 0);
	    am.cancel(sender);
	    context.stopService(intent);
	}
}
